# 多阶段构建 - 基础镜像
FROM python:3.11-slim AS base

# 设置环境变量
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

# 使用国内源并安装系统依赖
RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources && \
    sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources && \
    apt-get update && apt-get install -y \
    build-essential \
    curl \
    git \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Ollama安装阶段 - 独立缓存
FROM base AS ollama

# 安装Ollama
RUN curl -fsSL https://ollama.ai/install.sh | sh

# 工作目录
WORKDIR /app

# 依赖安装阶段
FROM ollama AS deps

# 复制依赖文件
COPY requirements.txt .

# 使用清华源安装Python依赖
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple/ -r requirements.txt

# 应用构建阶段
FROM ollama AS app

# 复制已安装的依赖
COPY --from=deps /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=deps /usr/local/bin /usr/local/bin

# 复制应用代码
COPY app/ ./app/
COPY templates/ ./templates/
COPY static/ ./static/
COPY config/ ./config/
COPY scripts/ ./scripts/
COPY app.py .

# 创建必要目录
RUN mkdir -p data/database data/documents data/vectors logs

# 设置权限
RUN chmod +x scripts/*.sh

# 暴露端口
EXPOSE 5002

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:5002/health || exit 1

# 启动命令
CMD ["bash", "scripts/docker-start.sh"] 